#!/bin/bash

# This file has the .sql extension, but it is actually launched as a shell
# script. This contortion is necessary because pg_regress normally uses
# psql to run the input scripts, and requires them to have the .sql
# extension, but we use a custom launcher script that runs the scripts using
# a shell instead.

TESTNAME=bitmaptest

. sql/config_test.sh

# Do an insert in master.
function before_standby
{
PGOPTIONS=${PGOPTIONS_UTILITY} $MASTER_PSQL <<EOF
CREATE TABLE tb1(a INT, b INT);
CREATE INDEX idx1 on tb1 USING bitmap(b);
CHECKPOINT;
EOF
}

# This script runs after the standby has been promoted. Old Master is still
# running.
function after_promotion
{
# The restart of master is done to force master and standby having
# same oid and relfilenode. pg_control file records NextRelfilenode
# which will be used on restart by master and standby uses the same
# after promotion.
pg_ctl -w -D $TEST_MASTER restart -m immediate >>$log_path 2>&1

PGOPTIONS=${PGOPTIONS_UTILITY} $MASTER_PSQL <<EOF
insert into tb1 select 0, 1 from generate_series(1, 128);
insert into tb1 select 0, 0 from generate_series(1, 64);
delete from tb1 where b = 1;
-- To create hole for generating UPDATE_WORD and UPDATE_WORDS wal
-- records.
vacuum tb1;
-- make sure vacuum worked
set gp_select_invisible to on;
select count(*) from tb1;
set gp_select_invisible to off;
-- each insert serves the purpose to generate the specific wal record
-- type for bitmap.
insert into tb1 values(0,0);
insert into tb1 values(0,0);
insert into tb1 values(0,1);
EOF

PGOPTIONS=${PGOPTIONS_UTILITY} $STANDBY_PSQL <<EOF
insert into tb1 select 2, 3 from generate_series(1, 128);
insert into tb1 select 2, 2 from generate_series(1, 64);
delete from tb1 where b = 3;
-- To create hole for generating UPDATE_WORD and UPDATE_WORDS wal
-- records.
vacuum tb1;
-- make sure vacuum worked
set gp_select_invisible to on;
select count(*) from tb1;
set gp_select_invisible to off;
-- each insert serves the purpose to generate the specific wal record
-- type for bitmap.
insert into tb1 values(2,2);
insert into tb1 values(2,2);
insert into tb1 values(2,3);
EOF
}

# Compare results generated by querying new master after rewind
function after_rewind
{
PGOPTIONS=${PGOPTIONS_UTILITY} $MASTER_PSQL -c "SELECT count(*) from tb1;"
PGOPTIONS=${PGOPTIONS_UTILITY} $MASTER_PSQL -c "SET enable_seqscan=off; SET optimizer_enable_tablescan=off; SELECT count(*) from tb1 WHERE b=2;"
PGOPTIONS=${PGOPTIONS_UTILITY} $MASTER_PSQL -c "SET enable_seqscan=off; SET optimizer_enable_tablescan=off; SELECT count(*) from tb1 WHERE b=3;"
}

# Run the test
. sql/run_test.sh
